package com.yixing.tech.system.service.impl;

import com.yixing.tech.common.enums.Status;
import com.yixing.tech.common.enums.YesOrNo;
import com.yixing.tech.common.service.AbstractUserDetailsService;
import com.yixing.tech.common.security.AuthenticationUser;
import com.yixing.tech.common.service.SysAuthUserService;
import com.yixing.tech.common.utils.SpringContextUtil;
import com.yixing.tech.system.po.SystemUser;
import com.yixing.tech.system.service.IPortalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * DefaultSysAuthUserServiceImpl
 *
 * @author <a href="mailto:brucezhang_jjz@163.com">zhangj</a>
 * @since 1.0.0
 */
@Service
public class SystemUserDetailsServiceImpl extends AbstractUserDetailsService {

    @Autowired
    private SysAuthUserService sysAuthUserService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IPortalService portalService;


//    private final SysAuthUserService sysAuthUserService;
//
//    private MongoTemplate mongoTemplate;
//
//    public SystemUserDetailsServiceImpl(SysAuthUserService sysAuthUserService) {
//        this.sysAuthUserService = sysAuthUserService;
//    }
//
//    public MongoTemplate getMongoTemplate() {
//        if(mongoTemplate == null) {
//            mongoTemplate = SpringContextUtil.getBean(MongoTemplate.class);
//        }
//        return mongoTemplate;
//    }

    /**
     * 内部的加载用户信息
     */
    @Override
    protected AuthenticationUser loadUserByUsernameInternal(String username) {
        Criteria andCriteria = new Criteria();
        Criteria orCriteria = new Criteria();
        orCriteria.orOperator(Criteria.where("loginName").is(username), Criteria.where("phone").is(username));
        andCriteria.andOperator(
                Criteria.where("status").is(Status.def.ordinal()).and("isDelete").ne(YesOrNo.YES.ordinal()),
                // TODO 租户
//                        .and("tenantId").is(tenantId),
                orCriteria);
        return mongoTemplate.findOne(Query.query(andCriteria), SystemUser.class);
    }
}
